/**
 * media-service
 * @authors 杨兴洲（of2502）
 * @date    2017/5/31 0031 10:45
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */

import Media from "../model/media";
import WeixinMaterialService from "./weixin-material-service";

export default class MediaService {
    /**
     * 创建Media
     * @param appID
     * @param media_id
     * @param url
     * @param aliUrl
     * @param type
     * @returns {Promise<any>}
     */
    static async createMedia({appID, media_id, url,aliUrl, type}: { appID: string, media_id: string, url: string,aliUrl?:string, type: string }): Promise<any> {
        return await Media.findOneAndUpdate({media_id}, {appID, media_id, url,aliUrl, type}, {upsert: true});
    }

    /**
     * 删除Media
     */
    static async deleteMedia(media_id: string): Promise<any> {
        return new Promise((resolve, reject) => {
            Media.findOne({media_id},function (err,data) {
                data && data.remove()
            });
        });
    }

    /**
     * 删除公众号所有Media
     */
    static async deleteUserMedia(appID): Promise<any> {
        return await Media.remove({appID});
    }

    /**
     * 获取素材
     * todo:获取不到,走微信接口下载(视频,音频,图片),走cdn换取链接,绑定返回
     */
    static async getDetail(media_id: string): Promise<any> {
        console.log("获取素材",media_id);
        return await Media.findOne({media_id});
    }

    /**
     * 同步素材
     */
    static async syncMedia({appID, access_token, type, page}): Promise<any> {
        const PAGE_SIZE = 20;
        let {item, item_count, total_count}:any = await WeixinMaterialService.getList({
            access_token,
            type,
            offset: (page - 1) * PAGE_SIZE,
            count: PAGE_SIZE
        });
        console.log(item);
        await Promise.all(item.map(({media_id, url}) => MediaService.createMedia({appID, media_id, url, type})));
        if (item_count >= PAGE_SIZE) return await MediaService.syncMedia({appID, access_token, type, page: ++page});
    }
}
